<script setup lang="ts">
import { ref, onMounted, h } from 'vue';
import { Page } from '@vben/common-ui';
import { NDataTable, NButton, NModal, NForm, NFormItem, NInput, useMessage } from 'naive-ui';
import { getResourceList, createResource, updateResource, deleteResource, getResourceDetail, type Resource } from '#/api/authserver/resource';

const columns = [
  { key: 'id', title: '资源ID' },
  { key: 'code', title: '资源编码' },
  { key: 'name', title: '资源名称' },
  { key: 'description', title: '描述' },
  { key: 'type', title: '类型' },
  { key: 'clientId', title: '客户端ID' },
  { key: 'parentId', title: '父资源ID', render: (row: any) => row.parentId || '-' },
  { key: 'actions', title: '操作列表', render: (row: any) => (row.actions || []).join(', ') },
  {
    key: 'actions',
    title: '操作',
    render(row: any) {
      return [
        h(NButton, { size: 'small', type: 'primary', onClick: () => handleDetail(row) }, { default: () => '详情' }),
        h(NButton, { size: 'small', type: 'info', class: 'ml-2', onClick: () => handleEdit(row) }, { default: () => '编辑' }),
        h(NButton, { size: 'small', type: 'error', class: 'ml-2', onClick: () => handleDelete(row) }, { default: () => '删除' }),
      ];
    },
  },
];

// 详情表格列定义
const detailColumns = [
  { key: 'field', title: '字段' },
  { key: 'value', title: '值' },
];

const data = ref<Resource[]>([]);
const loading = ref(false);
const message = useMessage();

// 弹窗相关
const showModal = ref(false);
const modalType = ref<'create'|'edit'|'detail'>('create');
const modalTitle = ref('');
const formModel = ref<Resource>({
  code: '',
  name: '',
  description: '',
  type: '',
  clientId: '',
  parentId: undefined,
  actions: []
});
const formLoading = ref(false);
const detailData = ref<any[]>([]);

async function fetchData() {
  loading.value = true;
  try {
    const res = await getResourceList();
    data.value = res.result?.items || [];
  } catch (error) {
    console.error('获取资源列表失败:', error);
    message.error('获取资源列表失败');
    data.value = [];
  } finally {
    loading.value = false;
  }
}

onMounted(fetchData);

function handleCreate() {
  modalType.value = 'create';
  modalTitle.value = '新建资源';
  formModel.value = {
    code: '',
    name: '',
    description: '',
    type: '',
    clientId: '',
    parentId: undefined,
    actions: []
  };
  showModal.value = true;
}

function handleEdit(row: Resource) {
  modalType.value = 'edit';
  modalTitle.value = '编辑资源';
  formModel.value = {
    ...row,
  };
  showModal.value = true;
}

async function handleDetail(row: Resource) {
  modalType.value = 'detail';
  modalTitle.value = '资源详情';
  formLoading.value = true;
  try {
    const res = await getResourceDetail(row.id!);
    console.log('Detail API Response:', res);

    if (res.result) {
      const resource = res.result;
      formModel.value = {
        id: resource.id,
        code: resource.code,
        name: resource.name,
        description: resource.description,
        type: resource.type,
        clientId: resource.clientId,
        parentId: resource.parentId,
        actions: resource.actions,
        createdAt: resource.createdAt,
        createdBy: resource.createdBy,
      };
    } else {
      formModel.value = res.result || {};
    }

    // 转换为表格数据格式
    detailData.value = [
      { field: '资源ID', value: formModel.value.id || '-' },
      { field: '资源编码', value: formModel.value.code || '-' },
      { field: '资源名称', value: formModel.value.name || '-' },
      { field: '描述', value: formModel.value.description || '-' },
      { field: '类型', value: formModel.value.type || '-' },
      { field: '客户端ID', value: formModel.value.clientId || '-' },
      { field: '父资源ID', value: formModel.value.parentId || '-' },
      { field: '操作列表', value: Array.isArray(formModel.value.actions) ? formModel.value.actions.join(', ') : '-' },
      { field: '创建时间', value: formModel.value.createdAt || '-' },
      { field: '创建者', value: formModel.value.createdBy || '-' },
    ];

    showModal.value = true;
  } catch (error) {
    console.error('获取详情失败:', error);
    message.error('获取详情失败');
  } finally {
    formLoading.value = false;
  }
}

async function handleDelete(row: Resource) {
  if (confirm('确定要删除该资源吗？')) {
    try {
      await deleteResource(row.id!);
      message.success('删除成功');
      fetchData();
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  }
}

async function handleModalOk() {
  formLoading.value = true;
  try {
    // 验证必填字段
    if (!formModel.value.code || !formModel.value.name) {
      message.error('请填写资源编码和资源名称');
      return;
    }

    if (modalType.value === 'create') {
      await createResource(formModel.value);
      message.success('新建成功');
    } else if (modalType.value === 'edit') {
      await updateResource(formModel.value.id!, formModel.value);
      message.success('编辑成功');
    }
    showModal.value = false;
    fetchData();
  } catch (error) {
    console.error('操作失败:', error);
    message.error(modalType.value === 'create' ? '新建失败' : '编辑失败');
  } finally {
    formLoading.value = false;
  }
}
</script>

<template>
  <Page description="资源管理" title="资源管理">
    <div class="mb-4 flex justify-end">
      <NButton type="primary" @click="handleCreate">新建资源</NButton>
    </div>
    <NDataTable :columns="columns" :data="data" :loading="loading" />
    <NModal v-model:show="showModal" :title="modalTitle" preset="dialog" :loading="formLoading" :mask-closable="false" :style="{ width: '800px' }">
      <NForm :model="formModel" label-width="100" v-if="modalType !== 'detail'">
        <NFormItem label="资源编码" path="code">
          <NInput v-model:value="formModel.code" />
        </NFormItem>
        <NFormItem label="资源名称" path="name">
          <NInput v-model:value="formModel.name" />
        </NFormItem>
        <NFormItem label="描述" path="description">
          <NInput v-model:value="formModel.description" type="textarea" />
        </NFormItem>
        <NFormItem label="类型" path="type">
          <NInput v-model:value="formModel.type" />
        </NFormItem>
        <NFormItem label="客户端ID" path="clientId">
          <NInput v-model:value="formModel.clientId" />
        </NFormItem>
        <NFormItem label="父资源ID" path="parentId">
          <NInput v-model:value="formModel.parentId" />
        </NFormItem>
        <NFormItem label="操作列表" path="actions">
          <NInput v-model:value="formModel.actions" placeholder="用英文逗号分隔" />
        </NFormItem>
      </NForm>
      <NDataTable v-else :columns="detailColumns" :data="detailData" :bordered="false" />
      <template #action v-if="modalType !== 'detail'">
        <NButton type="primary" :loading="formLoading" @click="handleModalOk">确定</NButton>
        <NButton class="ml-2" @click="() => (showModal = false)">取消</NButton>
      </template>
      <template #action v-else>
        <NButton @click="() => (showModal = false)">关闭</NButton>
      </template>
    </NModal>
  </Page>
</template>

<style scoped></style>
